package com.testcase;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.csvreader.CsvReader;
import com.sensetecnic.client.SenseTecnicClient;
import com.sensetecnic.client.SenseTecnicException;

public class SensorListTableView extends Activity {
	
	private List<String> senList;
	private List<List<String>> dataList;
	private int id;
	private SensorNames bothTitles;
	
	//Margins for TextView and TableRow
	private static final int leftMargin = 2;
	private static final int topMargin = 2;
	private static final int rightMargin = 2;
	private static final int bottomMargin = 2;
	
	//Padding for TextView
	private static final int leftPad = 5;
	private static final int topPad = 5;
	private static final int rightPad = 5;
	private static final int bottomPad = 5;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.tablepostsen);
		
		//Retrieve information from other activities
		@SuppressWarnings("unchecked")
		HashMap<String, List<String>> sensor = (HashMap<String, List<String>>) getIntent().getSerializableExtra("sensorList");
		senList = sensor.get("senList");
		
		//Using negative one as it is a number that should never be sent from another activity
		//Don't do anything to protect from negative one though
		id = (int) getIntent().getIntExtra("index", -1);
		bothTitles = new SensorNames(senList.get(id));
		
		try {
			//getData from Sense Tecnic
			dataList = this.getData(bothTitles.getTitle());
		} catch(SenseTecnicException e) {
			TableLayout t = (TableLayout) findViewById(R.id.table);
			TableRow tr = new TableRow(this);
			TextView tv = new TextView(this);
			if(e.toString().contains("Unauthorized")) {
				tv.setText("Username/Password Incorrect");
			}
			else {
				tv.setText(e.toString());
			}
			tr.addView(tv);
			t.addView(tr);
			return;
		} catch(IOException e) {
			TableLayout t = (TableLayout) findViewById(R.id.table);
			TableRow tr = new TableRow(this);
			TextView tv = new TextView(this);
			if(e.toString().contains("Unauthorized")) {
				tv.setText("Username/Password Incorrect");
			}
			else {
				tv.setText(e.toString());
			}
			tr.addView(tv);
			t.addView(tr);
			return;
		}
		
		//Design the table to have borders
		TableLayout table = (TableLayout) findViewById(R.id.table);
		//Populate the table with the data given
		//the datalist size is used add tablerows for each row in sense tecnic
		for(int i=0; i < dataList.size(); i++) {
	        TableRow tableRow = populateRow(dataList.get(i), getApplicationContext());
	        table.addView(tableRow);
		}		
	}
	
	//Function to get and read CSV data
	public List<List<String>> getData(String sensor) throws SenseTecnicException, IOException {
		SenseTecnicClient client;
		List<List<String>> tmpList = new ArrayList<List<String>>();
		
		//Sense Part
		client = new SenseTecnicClient();
		client.setStsBaseUrl("http://demo.sensetecnic.com/SenseTecnic/api");
		
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    	Resources reso = getResources();
    	String user = pref.getString(reso.getString(R.string.stsUsernameKey), null);
    	String pass = pref.getString(reso.getString(R.string.stsPasswordKey), null);
		
		String csvData = client.getSensorDataCsv(sensor, 10, user, pass);
		
		CsvReader reader = new CsvReader(new StringReader(csvData));
		// populating the lists
		while (reader.readRecord()) {
			List<String> rowList = new ArrayList<String>();
			for (int i=0; i<reader.getColumnCount(); i++) {
				rowList.add(reader.get(i).toString());
			}
			tmpList.add(rowList);
		}
		return tmpList;
	}
	
	//Function to populate each tablerow
	public static TableRow populateRow(List<String> dataEnt, Context activity) {
		TableRow tr = new TableRow(activity);		
		//Draw margins
		TableLayout.LayoutParams rowMargins = new TableLayout.LayoutParams(
				TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
		rowMargins.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
		tr.setLayoutParams(rowMargins);
		for(int i = 0; i < dataEnt.size(); i++) {
			TextView tv = new TextView(activity);
			//Design TextView
			tv.setText(dataEnt.get(i).toString());
			tv.setPadding(leftPad, topPad, rightPad, bottomPad);
			tv.setBackgroundColor(R.color.light_gray);
			TableRow.LayoutParams textMargins = new TableRow.LayoutParams();
			textMargins.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
			tr.addView(tv, textMargins);
		}
		return tr;
	}
}
